<template>
	<div>
		<div class="confirm-wrapper">
			<div class="operate xc-w-100p xc-flex xc-row-between xc-margin-b-15 xc-margin-right-70">
				<div class="" style='float:left'>地址：{{address_detail2 ? address_detail2: '无'}}</div>
				<div class="">
					<el-button v-if="!unableSet" @click="confirm" type="primary">确认</el-button>
				</div>
			</div>
			<div>
				<el-input clearable v-show="!unableSearch" class='r-result' size="small" type="text" placeholder="请输入公司地址"
					:id="suggestId" style="width:300px;" v-model="address_detail" />
			</div>
			<div :id="randomId" class='l-map'></div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				address_detail: null, //详细地址
				address_detail2: null, //详细地址
				// showFlag: false,
				resultObj: {}, //坐标逆解析结果对象(根据经纬度获取地址)
				curPoint: {}, //当前选中的坐标经纬度
				scrollTop: null,
				scrollLeft: null,
				randomId: "",
				suggestId: "",
			}
		},
		props: {
			defaultPoint: {
				type: Object,
				default: null
			}, //从父组件传入已知经纬度信息，用于编辑地图
			unableSearch: {
				type: Boolean,
				default: false
			}, //用于只查看地图时模态框只读，不带搜索和确定按钮
			unableSet: {
				type: Boolean,
				default: false
			}
		},
		// created() {
		// },
		mounted() {
			this.randomId = this.randomString()
			this.suggestId = this.randomString2()
			this.show();
		},
		methods: {
			show() {
				document.body.style.overflow = 'hidden'
				this.scrollTop = document.documentElement.scrollTop
				this.scrollLeft = document.documentElement.scrollLeft
				window.scrollTo(0, 0)
				// this.showFlag = true
				this.$nextTick(() => {
					setTimeout(() => {
						//初始化地图
						var th = this
						//第一次点开地图弹框，进行地图的实例化
						var map = new BMap.Map(this.randomId);
						// 初始化地图,设置中心点坐标，
						if (
							this.defaultPoint &&
							this.defaultPoint.lng &&
							this.defaultPoint.lat
						) {
							map.clearOverlays()
							var point = new BMap.Point(
								this.defaultPoint.lng,
								this.defaultPoint.lat
							)
							map.centerAndZoom(point, 12)
							map.enableScrollWheelZoom(); //启动鼠标滚轮操作
							let marker = new BMap.Marker(point)
							map.addOverlay(marker)
							this.address_detail2 = this.defaultPoint.address
						} else {
							var point = new BMap.Point(110.180155, 22.636147); // 创建点坐标，
							map.centerAndZoom(point, 12);
							map.enableScrollWheelZoom(); //启动鼠标滚轮操作
							let marker = new BMap.Marker(point)
							map.addOverlay(marker)
						}
						this.address_detail = ""
						var ac = new BMap.Autocomplete(
							//建立一个自动完成的对象
							{
								"input": this.suggestId,
								"location": map
							}
						)
						var myValue
						ac.addEventListener("onconfirm", function(e) {
							//鼠标点击下拉列表后的事件
							var _value = e.item.value; //获取选中的地址信息
							myValue = _value.province + _value.city + _value.district + _value.street + _value.business; //拼接成具体地址
							th.address_detail = th.address_detail2 = myValue
							setPlace();
						});

						function setPlace() {
							map.clearOverlays(); //清除地图上所有覆盖物
							function myFun() {
								if (local.getResults().getPoi(0)) {
									th.curPoint = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
									map.centerAndZoom(th.curPoint, 12);
									map.addOverlay(new BMap.Marker(th.curPoint)); //添加标注
								} else {}
							}
							var local = new BMap.LocalSearch(map, { //智能搜索
								onSearchComplete: myFun
							});
							local.search(myValue);
						}
						//测试输出坐标（指的是输入框最后确定地点的经纬度）
						if (this.unableSearch == false) {
							map.addEventListener("click", function(e) {
								map.clearOverlays();
								th.curPoint = new BMap.Point(e.point.lng, e.point.lat)
								let marker = new BMap.Marker(th.curPoint)
								map.addOverlay(marker)
								var geoc = new BMap.Geocoder();
								var pt = e.point;
								geoc.getLocation(pt, function(rs) {
									var addComp = rs.addressComponents;
									th.address_detail2 = addComp.province + addComp.city + addComp.district + addComp.street + addComp
										.streetNumber;
								});
							})
						}
					}, 500);
				})
			},
			// hide() {
			// 	var map = new BMap.Map(this.randomId);
			// 	// this.showFlag = false
			// 	document.body.style.overflow = 'auto'
			// 	if (this.scrollTop !== null && this.scrollLeft !== null) {
			// 		window.scrollTo(this.scrollLeft, this.scrollTop)
			// 	}
			// 	this.address_detail = ''
			// 	if (!this.resultObj.lng && !this.resultObj.lat) {
			// 		map.clearOverlays()
			// 		if (
			// 			this.defaultPoint &&
			// 			this.defaultPoint.lng &&
			// 			this.defaultPoint.lat
			// 		) {
			// 			this.drawDefaultPoint()
			// 		} else {
			// 			let center = new BMap.Point(116.398395, 39.132039)
			// 			map.centerAndZoom(center, 12)
			// 		}
			// 	}
			// },
			confirm() {
				if (!this.curPoint.lng && !this.curPoint.lat) {
					this.$message({
						message: '请在地图上标记位置点',
						type: 'info'
					})
					return
				}
				//给经纬度获取详细地址
				this.geoc = new BMap.Geocoder()
				this.geoc.getLocation(this.curPoint, res => {
					// this.showFlag = false
					document.body.style.overflow = 'auto'
					if (this.scrollTop !== null && this.scrollLeft !== null) {
						window.scrollTo(this.scrollLeft, this.scrollTop)
					}
					if (res !== null) {
						this.resultObj = {
							address: this.address_detail2,
							// address: res.surroundingPois[0].address,
							lng: res.point.lng,
							lat: res.point.lat,
							addressComponents: res.addressComponents //省市县
						}
						this.$emit('getLocation', this.resultObj)
					} else {
						this.$message({
							message: '未能获取位置详细信息',
							type: 'warning'
						})
						if (this.address_detail) {
							this.resultObj = {
								address: this.address_detail,
							}
						} else {
							this.resultObj = this.curPoint
						}
						this.$emit('getLocation', this.resultObj)
					}
				})
			},
			drawDefaultPoint() {
				var map = new BMap.Map(this.randomId);
				map.clearOverlays()
				this.curPoint = new BMap.Point(
					this.defaultPoint.lng,
					this.defaultPoint.lat
				)
				map.centerAndZoom(this.curPoint, 12)
				let marker = new BMap.Marker(this.curPoint)
				map.addOverlay(marker)
				this.address_detail2 = this.defaultPoint.address //详情时从父组件传过来的地址
			},
			//生成随机id数（因为一个页面可能多次用到地图组件，保证其地图加载时能找到唯一的id）
			randomString() {
				var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
				var maxPos = $chars.length
				var pwd = ''
				for (let i = 0; i < 32; i++) {
					pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
				}
				return pwd
			},
			randomString2() {
				var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
				var maxPos = $chars.length
				var pwd = ''
				for (let i = 0; i < 32; i++) {
					pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
				}
				return pwd
			},
			clearResult() {
				this.resultObj = {}
			}
		}
	}
</script>

<style scoped>
	.confirm {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 990;
		background-color: rgba(0, 0, 0, 0.3);
		padding: 40px 40px 40px;
	}

	.confirm.confirm-fade-enter-active {
		animation: confirm-fadein 0.3s;
	}

	.confirm .confirm-wrapper {
		position: relative;
		width: 100%;
		height: 100%;
		z-index: 222;
		background: #fff;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
	}

	.confirm .confirm-wrapper .topoperate {
		position: absolute;
		height: 50px;
		width: 100%;
		top: 0;
		padding: 10px 20px;
		background: #fff;
		z-index: 99;
	}

	.confirm .confirm-wrapper .operate {
		/* position: absolute; */
		width: 100%;
		/* bottom: 0; */
		padding: 10px 20px;
		background: #fff;
		text-align: center;
	}

	.confirm .confirm-wrapper .operate .leftSide {
		float: left;
		line-height: 40px;
	}

	.confirm .confirm-wrapper .operate .rightSide {
		float: right;
	}

	.l-map {
		width: 100%;
		text-align: center;
		margin: 0 auto;
		height: 500px;
	}

	.r-result {
		width: 340px;
		z-index: 999;
		position: fixed;
		/* top: 100px;
		left: 70px; */
	}

	@keyframes confirm-fadein {
		0% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}
</style>
<style>
	/* 关键字下拉框 */
	.tangram-suggestion-main {
		z-index: 9999 !important;
	}

	/* 去掉坐下面默认百度logo版权 */
	.BMap_cpyCtrl {
		display: none;
	}

	.anchorBL {
		display: none;
	}

	/* 标题样式 */
	.all_blue2 {
		width: 3px;
		height: 24px;
		background: #6ab2ff;
	}
</style>